import { ContainerService } from "shared/component/container/ContainerService";
import Log4R from "shared/component/log/Log4R";
const loginfo = Log4R.getLog('info');
/**
 * 2D物理限制
 */
export class Physical2DServiceImpl extends ContainerService<Ctn.Physical2DService, Ctn.Physical2DEntity> implements Ctn.Physical2DService {
    serverCalls: (keyof this)[] = [];
    serviceName: keyof Ctn.Services = "physical2DService";
    /** 2D物理限制basePart */
    private constraintsPart?: BasePart;

    /**
     * 添加2D物理限制
     * @param part 被限制的part 
     * @param attachment1Name 配限制的part的att
     */
    constraint(part: BasePart, attachment1Name: string) {
        let physical2DConstraint = part.FindFirstChild('physical2DConstraint');
        const attachment1 = part.WaitForChild(attachment1Name);
        if (!attachment1?.IsA('Attachment')) {
            // loginfo?.info('part:', part)
            throw ('can not find ' + attachment1Name + ' as a attachment in ')
        }
        if (!physical2DConstraint?.IsA('PlaneConstraint')) {
            part.FindFirstChild('physical2DConstraint')?.Destroy();
            const physical2DConstraint = new Instance('PlaneConstraint', part);
            physical2DConstraint.Name = 'physical2DConstraint';
            while (!this.constraintsPart) {
                wait(0.5);
            }
            physical2DConstraint.Attachment0 = this.constraintsPart?.FindFirstChild('attachment0') as Attachment
            physical2DConstraint.Attachment1 = attachment1;
        }
    }
    private get2dConstraintsPart() {
        if (this.constraintsPart?.IsDescendantOf(game.Workspace)) {
            return this.constraintsPart
        } else {
            let configFolder = game.Workspace.FindFirstChild(this.serviceName);
            if (!configFolder) {
                configFolder = new Instance('Folder', game.Workspace);
                configFolder.Name = this.serviceName;
            }
            this.constraintsPart = new Instance('Part');
            this.constraintsPart.Anchored = true;
            this.constraintsPart.CanCollide = false;
            this.constraintsPart.CanTouch = false;
            this.constraintsPart.Name = "constraintsPart";
            this.constraintsPart.Parent = configFolder;
            const attachment0 = new Instance('Attachment', this.constraintsPart);
            attachment0.Name = "attachment0";
            attachment0.Orientation = new Vector3(0, 90, 0)
            return this.constraintsPart
        }
    }
    public init(): void {
        if (this.runInLocal()) {
            this.get2dConstraintsPart();
        }

    }

    public run(): void {

    }
}